import { refreshToken } from '@/api/user'
import { useUserStore } from '@/store/modules/user'
import { ElMessageBox } from 'element-plus'
import { watch } from 'vue'
import { useRoute } from 'vue-router'

export default () => {
  // 激活路由对象
  const route = useRoute()

  // 路由白名单
  const whiteList = [
    '/login/index',
    '/login/roles',
    '/login/forget',
    '/login/resuccess',
    '/login/register',
    '/auth-redirect',
  ]

  // 定时器
  let timer = null

  // 最后一次点击时间
  let lastTime = new Date().getTime()

  // 当前时间
  let currentTime = new Date().getTime()

  // 允许最长未操作时间
  const timeOut = 90 * 60 * 1000

  function handleReset() {
    if (timer) {
      clearInterval(timer)
      timer = null
    }

    // 重新赋值最后一次点击时间，清除定时器，重新开始定时器
    lastTime = new Date().getTime()

    if (!timer) {
      handleInterval()
    }
  }

  // 单击事件
  document.onclick = () => {
    handleReset()
  }

  // 双击事件
  document.ondblclick = () => {
    handleReset()
  }

  // 按下鼠标键时触发
  document.onmousedown = () => {
    handleReset()
  }

  // 释放按下的鼠标键时触发
  document.onmouseup = () => {
    handleReset()
  }

  // 鼠标移动事件
  document.onmousemove = () => {
    handleReset()
  }

  // 移入事件
  document.onmouseover = () => {
    handleReset()
  }

  // 移出事件
  document.onmouseout = () => {
    handleReset()
  }

  // 移入事件
  document.onmouseenter = () => {
    handleReset()
  }

  // 移出事件
  document.onmouseleave = () => {
    handleReset()
  }

  function handleInterval() {
    if (whiteList.includes(route.path)) {
      return
    }

    // 设置定时器
    timer = setInterval(() => {
      // 重新设置当前时间
      currentTime = new Date().getTime()

      // 长时间没有操作，自动退出
      if (currentTime - lastTime > timeOut) {
        // 清除定时器，防止内存泄漏
        clearInterval(timer)

        const UserStore = useUserStore()
        ElMessageBox({
          title: '',
          message: '登录过期，请重新登录！',
          showClose: false,
          confirmButtonText: '点击重新登录',
          type: 'warning',
          autofocus: false,
          async beforeClose(action, instance, done) {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              const res = await refreshToken({ refreshToken: UserStore.row.refreshToken })
              UserStore.token = res.data.data.row.tokenValue
              UserStore.row = { ...res.data.data.row, tokenStartTime: new Date().getTime() }
              instance.confirmButtonLoading = false
              handleReset()
              done()
            }
          },
        })
      }
    }, 1000)
  }

  // 一开始就执行程序
  handleInterval()

  watch(
    () => route.name,
    (value) => {
      if (['forget', 'resuccess', 'register', 'roles', 'index'].includes(value as string)) {
        clearInterval(timer)
      }
    },
    { immediate: true },
  )
}
